package com.example.captcha.controller;

import cn.hutool.captcha.CaptchaUtil;
import cn.hutool.captcha.LineCaptcha;
import com.example.captcha.model.CaptchaProperties;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.http.HttpSession;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.io.IOException;
import java.util.Date;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: Li_yizYa
 * Date: 2025/7/14
 * Time: 15:53
 */
@RestController
@RequestMapping("/captcha")
public class CaptchaController {

    @Autowired
    private CaptchaProperties cp;

    // 一分钟
    private static final Long VALID_TIME_OUT = (long) (60 * 1000);

    @GetMapping("/getCaptcha")
    public void getCaptcha(HttpSession session, HttpServletResponse response){
        // 生成验证码
        LineCaptcha lineCaptcha = CaptchaUtil.createLineCaptcha(cp.getWidth(), cp.getHeight());
        // 输出生成的验证码
        String code = lineCaptcha.getCode();
        System.out.println("生成验证码: " + code);
        // 存储 session
        session.setAttribute(cp.getSession().getKey(), code);
        session.setAttribute(cp.getSession().getDate(), new Date());

        try {
            // 把验证码写到浏览器
            lineCaptcha.write(response.getOutputStream());
            response.setContentType("image/jpeg");
            response.setCharacterEncoding("utf-8");
            // 防止缓存
            response.setHeader("Pragma", "No-cache");
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    @RequestMapping("/check")
    public Boolean check(HttpSession session, String captcha) {
        if (!StringUtils.hasLength(captcha)) {
            return false;
        }

        String code = (String)session.getAttribute(cp.getSession().getKey());
        Date date = (Date)session.getAttribute(cp.getSession().getDate());

        // session 过期 date 就为 null
        if (date == null || (System.currentTimeMillis() - date.getTime()) > VALID_TIME_OUT) {
            return false;
        }
        return captcha.equalsIgnoreCase(code);
    }
}
